#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time
from autoapi.core.path_conf import autoapi_path
from autoapi.core.get_conf import autoapi_config
from autoapi.utils.rich_console import console
from autoapi.common.log import log


def clean_testcases():
    """清理指定项目下的测试用例文件(只删除test_*.py文件)"""
    project_case_path = os.path.join(
        autoapi_path.testcase_dir, autoapi_config.PROJECT_NAME
    )

    if not os.path.isdir(project_case_path):
        log.error(f"测试用例目录不存在: {project_case_path}")
        return 0

    console.print("⏳ 正在清理测试用例...")
    log.info("⏳ 正在清理测试用例...")
    time.sleep(2)

    deleted_count = 0
    for root, dirs, files in os.walk(project_case_path):
        for file in files:
            if file.startswith("test_") and file.endswith(".py"):
                file_path = os.path.join(root, file)
                try:
                    os.remove(file_path)
                    console.print(f"🗑️ 已删除: {file_path}")
                    log.info(f"🗑️ 已删除: {file_path}")
                    deleted_count += 1
                except Exception as e:
                    console.print(f"⚠️ 删除失败: {file_path}, 原因: {e}")
                    log.warning(f"⚠️ 删除失败: {file_path}, 原因: {e}")

    console.print(f"✅ 清理完成，共删除 {deleted_count} 个测试用例文件")
    log.info(f"✅ 清理完成，共删除 {deleted_count} 个测试用例文件")
    return deleted_count
